package MediaPlayer;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class MPlayerThread extends Thread{
	Process process;
	BufferedWriter bw;
	BufferedReader br;
	String line;
	String mPlayerPath;
	String file;
	double length = 0;
	double timePos = 0;
	double tlength = 0;
	double ttimePos = 0;
	boolean done;
	public boolean paused;
	Thread t = new Thread(new Runnable(){
		@Override
		public void run() {
			try {
				while (true) {
				if (!paused) {
					tlength = 0;
					send("get_time_length");
					while(tlength == 0);
					length = tlength;
					
					ttimePos = 0;
					send("get_time_pos");
					while(ttimePos == 0);
					timePos = ttimePos;
				}
				
				Thread.sleep(1000);
				}
			} catch (InterruptedException ie)
			{}
		}
	});
	
	public MPlayerThread(String path, String file) {
		mPlayerPath = path;
		done = false;
		paused = true;
		t.start();
		this.file = file;
	}
	
	@Override
	public void run() {
		try{
			process = java.lang.Runtime.getRuntime().exec(new String[] { mPlayerPath, "-slave", file} );
			br = new BufferedReader( new InputStreamReader(process.getInputStream()) );
			bw = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
			paused = false;
			while ((line = br.readLine()) != null) {
				if (ttimePos == 0 && line.startsWith("ANS_TIME_POSITION=")) {
					ttimePos = Double.parseDouble(line.replaceAll("ANS_TIME_POSITION=", ""));
				}
				
				if (tlength == 0 && line.startsWith("ANS_LENGTH=")) {
					tlength = Double.parseDouble(line.replaceAll("ANS_LENGTH=", ""));
				}
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
		
	}
	
	public void send(String cmd) {
		if (paused) {
			cmd = "pausing " + cmd;
		}
        try {
            if (process != null) {
                bw.write(cmd + "\n");
                bw.newLine();
                bw.flush();
            }
        } catch (Exception e) { 
            e.printStackTrace();
        }            
    }
	
	public void finish() {
		send("quit");
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		done = true;
	}

	public double getPercent() {
		return 0;
	}
}
